<?php

namespace App\Library\Logic;

use App\Library\Requests\Coupon\CouponPageRequest;
use App\Models\CouponUserRelatedModel;
use Illuminate\Database\Eloquent\Builder;

class CouponUserRelatedLogic extends CouponUserRelatedModel
{
    public static function myPaging(CouponPageRequest $request): array
    {
        $builder = self::query()->leftJoin('coupon', 'coupon.id', 'coupon_user_related.coupon_id')
            ->where('user_id', USERID)->orderByDesc('coupon_user_related.created_at');
        if (!is_null($request->expired)) {
            if ($request->expired === true) {
                $builder->where(function (Builder $query) {
                    $query->whereNotNull('end_at')->where('end_at', '<=', now());
                });
            } else {
                $builder->where(function (Builder $query) {
                    $query->whereNull('end_at')->orWhere('end_at', '>', now());
                });
            }
            $request->offsetUnset('expired');
        }
        if (!is_null($request->price)) {
            $builder->where('coupon_user_related.status', 0)->where(function (Builder $query) use ($request) {
                $query->where(function (Builder $query) {
                    $query->whereNull('start_at')->orWhere('start_at', '<', now());
                })->where(function (Builder $query) use ($request) {
                    $query->where('full_amount', 0)->orWhere('full_amount', '>=', $request->price);
                });
            });
            $request->offsetUnset('price');
        }
        return paginate(helpBuilder($builder, $request)->paginate($request->limit, [
            'coupon_user_related.serial_number',
            'coupon_user_related.status',
            'coupon_user_related.created_at',
            'title',
            'amount',
            'full_amount',
            'start_at',
            'end_at',
        ]));
    }

    public static function receiveCount(int $couponId): int
    {
        return self::countByWhere(['couponId' => $couponId, 'userId' => USERID]);
    }

    public static function add(int $couponId): \Illuminate\Database\Eloquent\Model
    {
        return self::insertForModel(['coupon_id' => $couponId,
            'user_id' => USERID
        ]);
    }


    public static function getCount(int $couponId): int
    {
        return self::query()->where(['coupon_id' => $couponId, 'user_id' => USERID])->count();
    }

    /**
     * 未使用优惠券数量
     * @return int
     */
    public static function noUseCount(): int
    {
        return self::countByWhere(['status' => 0, 'userId' => USERID]);
    }
}
